#!/usr/bin/env bash

. $GVM_ROOT/scripts/functions

_gvm() {
	local cur prev opts base
	COMPREPLY=()
	cur="${COMP_WORDS[COMP_CWORD]}"
	base="${COMP_WORDS[0]}"
	cmd="${COMP_WORDS[1]}"
	subcmd="${COMP_WORDS[2]}"

	case "${cmd}" in
		pkgset)
			case "${subcmd}" in
				use|delete|empty)
					[[ "$gvm_go_name" == "" ]] && return 1
					[[ $COMP_CWORD > 3 ]] && return 1
					local version="$(for x in `$LS_PATH -1 $GVM_ROOT/pkgsets/$gvm_go_name`; do echo ${x} ; done )"
					COMPREPLY=( $(compgen -W "${version}" -- ${cur}) )
					return 0
				;;
				create|list)
					return 1
				;;
				*)
					opts="create delete empty list use"
					COMPREPLY=($(compgen -W "${opts}" -- ${cur}))
					return 0
				;;
			esac
		;;
		pkg)
			case "${subcmd}" in
				uninstall)
					[[ "$gvm_go_name" == "" ]] && return 1
					[[ "$gvm_pkgset_name" == "" ]] && return 1
					if [[ "$COMP_CWORD" == "3" ]]; then
						local version="$(for x in `$LS_PATH -1 $GVM_ROOT/pkgsets/$gvm_go_name/$gvm_pkgset_name/pkg.gvm`; do echo ${x} ; done )"
						COMPREPLY=( $(compgen -W "${version}" -- ${cur}) )
						return 0
					elif [[ "$COMP_CWORD" == "4" ]]; then
						local version="$(for x in `$LS_PATH -1 $GVM_ROOT/pkgsets/$gvm_go_name/$gvm_pkgset_name/pkg.gvm/${COMP_WORDS[3]}`; do echo ${x} ; done )"
						COMPREPLY=( $(compgen -W "${version}" -- ${cur}) )
						return 0
					fi
					return 1
				;;
				install|list)
					return 1
				;;
				*)
					opts="install list uninstall"
					COMPREPLY=($(compgen -W "${opts}" -- ${cur}))
					return 0
				;;
			esac
		;;
		install)
			[ ! -d $GVM_ROOT/archive/go ] && return 1
			[[ $COMP_CWORD > 2 ]] && return 1
			local version="$(builtin cd $GVM_ROOT/archive/go && for x in `git tag | $GREP_PATH -E "release|tip|go"`; do echo ${x} ; done )"
			COMPREPLY=( $(compgen -W "${version}" -- ${cur}) )
			return 0
		;;
		use|uninstall)
			[ ! -d $GVM_ROOT/gos ] && return 1
			[[ $COMP_CWORD > 2 ]] && return 1
			local installed_versions="$(for x in `$LS_PATH -1 $GVM_ROOT/gos`; do echo ${x} ; done )"
			COMPREPLY=( $(compgen -W "${installed_versions}" -- ${cur}) )
			return 0
		;;
		*)
			[[ $COMP_CWORD > 1 ]] && return 1
			opts="alias get install list listall uninstall use version"
			[[ "$gvm_go_name" != "" ]] && opts="alias cross diff get install list listall pkgset uninstall use version"
			[[ "$gvm_pkgset_name" != "" ]] && opts="alias cross diff get install list listall pkg pkgset uninstall use version"
			COMPREPLY=($(compgen -W "${opts}" -- ${cur}))
			return 0
		;;
	esac
}
complete -F _gvm gvm

